#!/usr/local/bin/python
# -*- coding: utf-8 -*-

'''
    用户对象定义
'''
import logging, traceback
from tornado.escape import json_encode, json_decode

import util, log
import const
from mysqlHelper import mysql
import time
import random
#import datetime
from user import UserManager
logger = logging.getLogger(__name__)

class store(util.SingleClass):
    goods_list = {}          #商品列表
    goods_dress_list = {}    #套装列表
    
    def __init__(self):
        pass
    
    def reload(self):
        '''加载商场数据'''
        store.goods_list.clear()
        store.goods_dress_list.clear()
        
        conn = mysql()
        sql = "SELECT * FROM t_goods"            
        goods_list = conn.getAll(sql)       
        for v in goods_list:
            if v['uptime']:
                v['uptime'] = str(v['uptime'])                    
            store.goods_list[v['goods_id']] = v
                            
        sql = "SELECT * FROM t_goods_dress"           
        goods_dress_list = conn.getAll(sql)
        for v in goods_dress_list:
            store.goods_dress_list[v['id']] = v
        
    #购买商品
    @staticmethod
    def buy_goods(request, owner_uid, goods):
        user = UserManager.get_user_by_request(request)
        if not user:
            return {'res':'user_is_null'}
        userinfo = user.m_userinfo
        buyer_uid = userinfo['uid']
        buyer_nickname = userinfo['nickname']
        owner = UserManager.get_user_wear_info(owner_uid)
        if not owner:
            return {'res':'user_is_null'}
        owner_nickname = owner['nickname']
         
        buy_gold = 0
        buy_money = 0 
        
        #统计购买需要的价格   并扣费  
        res = store.charge_goods(request, userinfo, goods)
        if res['res'] != True:
            return res            
        #更新游戏数值、个人商品信息并插入商品消费记录
        i = 0
        return_goods_info = []
        tmpPresentList = {0:[],1:[]} #赠送礼品列表
        totalNums = 0 #总计购买数量
        for v in goods:
            if v:                
                if i > 0:                
                    owner = UserManager.get_user_wear_info(owner_uid)
                    owner_nickname = owner['nickname']
                goods_id = v['id']
                nums = v['nums']
                totalNums = totalNums+nums
                         
                goods_info = store.get_goods_info(goods_id) 
                if not goods_info:
                    return {'res':'not_goods'}
                times = goods_info['time']               
                inlay_id = goods_info['inlay_id']    
                is_inlay = goods_info['is_inlay']           
                inlay_last_rec_id = 0          
                if inlay_id and is_inlay:#镶嵌商品消费记录             
                    inlay_info = store.get_goods_info(inlay_id)
                    if not inlay_info:
                        return {'res':'not_goods'}
                    money = store.total_buy_money(inlay_info, times, nums)
                    buy_gold = money['buy_gold']
                    buy_money = money['buy_money']
                                   
                    store.set_buy_log(buyer_uid, buyer_nickname, owner_uid, owner_nickname, inlay_info, buy_gold, buy_money)                   
                    inlay_last_rec_id = store.add_my_goods(buyer_uid, buyer_nickname, owner, inlay_info, times, nums, 0)
                    
                money = store.total_buy_money(goods_info, times, nums)
                buy_gold = money['buy_gold']
                buy_money = money['buy_money']
                
                store.set_buy_log(buyer_uid, buyer_nickname, owner_uid, owner_nickname, goods_info, buy_gold, buy_money)
                last_ids = store.add_my_goods(buyer_uid, buyer_nickname, owner, goods_info, times, nums, inlay_last_rec_id)        
             
                for vv in last_ids:
                    if goods_info['type_1'] == 'props' and goods_info['type_2'] != 'attire':
                        reNums = nums
                    else:
                        reNums = 1
                    return_goods_info.append({'id':goods_id, 'rec_id':vv , 'nums':reNums}) 
                
                #如果是礼品，则插入一条礼品信息到留言中,并增加用户和被赠送用户的相应数值              
                if goods_info['type_1'] == 'present' and owner_uid != buyer_uid:
                    
                    k=0
                    #初始化我的增加经验值
                    tmpMyAddexp = 0
                    #初始化对方增加经验值
                    tmpToUserAddcharm = 0
                  
                    for vv in last_ids:
                        tmpMyAddexp = tmpMyAddexp+const.Config_presen_get_exp()
                        tmpToUserAddcharm = tmpToUserAddcharm + const.Config_presen_get_charm()
                        tmpPresentList[goods_info['z_1']].append({'rec_id':vv, 'id':goods_id, 'got':0})
                        
                    
                    if tmpMyAddexp: 
                        tmpMyLogicMapObj = util.ConfigManager.getLogicInfo("default_logic")
                        util.ConfigManager.setLogicInfoVal_Exp(tmpMyLogicMapObj, tmpMyAddexp)
                        util.CountUserUtil.judgeAndEditExt('buy_goods', request, buyer_uid, tmpMyLogicMapObj)          #加经验
                        
                    if tmpToUserAddcharm:                        
                        tmpToUserLogicMapObj = util.ConfigManager.getLogicInfo("default_logic")                       
                        util.ConfigManager.setLogicInfoVal_Charm(tmpToUserLogicMapObj, tmpToUserAddcharm)
                        util.CountUserUtil.judgeAndEditExt('buy_goods', None, owner_uid, tmpToUserLogicMapObj)          #加魅力
                    
                    
            i += 1       
        #如果是送礼物则判断被赠送者的礼物数量是否达到最大值。
        #大小礼品的数量达到指定数量，需发一条礼品接收信息，用户只有通过领取才能摆在礼品架子上             
        if tmpPresentList[1]:
            store.add_present_msg(userinfo,owner,tmpPresentList[1],1)
        
        if tmpPresentList[0]:
            store.add_present_msg(userinfo,owner,tmpPresentList[0],0)
        
        if buyer_uid!=owner_uid:#统计获取礼品数量
            UserManager.updateUserCount('count_get_present', totalNums, owner_uid)
                
        tmpItembuyer = {"uid": buyer_uid, "nickname":buyer_nickname}
        tmpItemOwner = {"uid": owner_uid, "nickname":owner_nickname}
        return {'res':True, 'goods':return_goods_info, 'buyer': tmpItembuyer, 'owner': tmpItemOwner}
    
    @staticmethod
    def add_present_msg(userinfo,owner,tmpPresentList,z_1):
        owner_uid = owner['uid']
        tmpMy_present = owner['my_present']
        if not tmpMy_present:
            return None
        tmpMy_present = json_decode(tmpMy_present)
        
        if z_1 ==0:
            config_present_notice_nums = const.Config_small_present_notice_nums()
        if z_1 ==1:
            config_present_notice_nums = const.Config_big_present_notice_nums()
       
        if tmpMy_present:
            
            tmpPresentNums = store.get_my_goods_nums(tmpMy_present,{"z_1":z_1})    
          
        else:
            tmpPresentNums = len(tmpPresentList)                                  
        if (tmpPresentNums + len(tmpPresentList)) > config_present_notice_nums :                    
            start_nums = len(tmpPresentList) - ((tmpPresentNums + len(tmpPresentList)) - config_present_notice_nums)                   
            if start_nums<0 :
                start_nums=0

            to_user_guest_leaveword = UserManager.get_userinfo_record(owner_uid, 'uid,nickname,guest_leaveword')
            new_dic = {'title':'', 'content':const.Config_tip_present(), 'right':2, 'got':0, 'id':tmpPresentList[start_nums:len(tmpPresentList)]}
            tmpRes = UserManager.set_user_rec(userinfo, to_user_guest_leaveword, 'guest_leaveword', const.Config_leave_max, new_dic)#设置我的访问记录        
            
            tmpSendType = 'send_memo'
            tmpContent = '您有一条礼品信息'
            tmpNoticeDict = {
                            'rec_id':tmpRes.get('last_rec_id'),
                            'right':2,
                            'title':'',
                            'content':const.Config_tip_present(),
                            'timeline':time.strftime('%Y-%m-%d %H:%M:%S'),
                            'got':0,
                            'uid':userinfo.get('uid'), 
                            'nickname':userinfo.get('nickname'),
                            'id':tmpPresentList[start_nums:len(tmpPresentList)]
                            }              
            tmpContentAddtion = tmpNoticeDict        
            UserManager.pushSysInfoToSomebody(tmpSendType, tmpContent, tmpContentAddtion, *tuple([owner_uid]))    
    
    
    #购买计费
    @staticmethod
    def charge_goods(request, userinfo, goods, is_second=None):
        uid = userinfo['uid']
        nickname = userinfo['nickname']
        second_wear_list = {}
        buy_gold = buy_money = 0
        for v in goods:
            if v:
                goods_id = v['id']
                if is_second:
                    nums = 1
                else:
                    nums = v['nums']                      
                goods_info = store.get_goods_info(goods_id)               
                if not goods_info:
                    return {'res':'not_goods'}
                total = goods_info['total']               
                if total != -1 and total < nums:#数量不限
                    return {'res':'not_goods'} 
                if is_second:#如果是续费                    
                    times = v['time']
                    type_1 = goods_info['type_1']
                    type_2 = goods_info['type_2']
                    type_3 = goods_info['type_3']
                    if type_1 == 'props' and type_2 != 'attire':
                         return {'res':'props_not_rew'}
                    rec_id = v['rec_id']
                    #得到我的穿着信息
                    owner = UserManager.get_user_wear_info(uid)
                    if not owner['my_%s' % type_1]:
                        return {"res":"not_goods"}
                    my_goods = json_decode(owner["my_%s" % type_1]) 
                    if not my_goods.has_key(type_2):
                        return {"res":"not_goods"}                   
                    #得到我的商品列表       
                    my_goods_list = my_goods[type_2][type_3]['info']
                    #得到当前rec_id对应的商品信息
                    my_goods_info = store.get_my_goods_info_by_rec_id(rec_id, my_goods_list)
                    if not my_goods_info:
                        return {"res":"not_goods"}
                    #得到要续费的钱
                    money = store.total_buy_money(goods_info, times, 1, 1, None)#goods_info, times,nums,buy_second=None,total_inlay=True
                    in_money = {"buy_gold":0, "buy_money":0}
                    if my_goods_info.has_key('inlay'):
                        if my_goods_info['inlay']['inlay_id']:
                            inlay_id = my_goods_info['inlay']['inlay_id']
                            inlay_info = store.get_goods_info(inlay_id)
                            if not inlay_info:
                                return {'res':'not_goods'}
                            in_money = store.total_buy_money(inlay_info, times, 1, 1, None)
                    buy_gold += money['buy_gold'] + in_money['buy_gold']   #消费金币
                    buy_money += money['buy_money'] + in_money['buy_money']  #消费比索   
                    second_wear_list[rec_id] = {"buy_gold":buy_gold, "buy_money":buy_money, "my_goods_info":my_goods_info, 'times': times, 'goods_id':goods_id} 
                else:
                    times = goods_info['time']   
                    money = store.total_buy_money(goods_info, times, nums)
                    buy_gold += money['buy_gold']    #消费金币
                    buy_money += money['buy_money']   #消费比索                          

        #扣费         
        
        if userinfo['gold'] < buy_gold:
            return {'res':'not_gold'}#金币不足
        
        if userinfo['money'] < buy_money:    
            return {'res':'not_money'}#比索不足
        
        if not is_second:
            cmd = 'buy_goods'
        else:
            cmd = 'renew_goods'
        tmpLogicMapObj = util.ConfigManager.getLogicInfo("default_logic")                       #获取默认配置项
        util.ConfigManager.setLogicInfoVal_Gold(tmpLogicMapObj, buy_gold, bNegative=True)       #金币
        util.ConfigManager.setLogicInfoVal_Money(tmpLogicMapObj, buy_money, bNegative=True)     #比索        
        util.CountUserUtil.judgeAndEditExt(cmd, request, userinfo['uid'], tmpLogicMapObj)       #扣钱
        
        if is_second:
            if second_wear_list:
                for k, v in second_wear_list.iteritems():
                    goods_id = v['goods_id']
                    buy_gold = v['buy_gold']
                    buy_money += money['buy_money']   #消费比索    
                    goods_info = store.get_goods_info(goods_id)
                    if not goods_info:
                        return {'res':'not_goods'}
                    times = v['times']
                    store.set_buy_log(uid, nickname, uid, nickname, goods_info, buy_gold, buy_money, 1)                    
                    store.add_my_goods(uid, nickname, userinfo, goods_info, times, 1, 0, 1, k)
                    
        return {'res':True}
        
    #出售商品
    @staticmethod
    def sell_goods(request, goods):
        user = UserManager.get_user_by_request(request)
        if not user:
           return {'res':'user_is_null'}       
        userinfo = user.m_userinfo
        tmpList = []
        for v in goods:
            if not v:
                continue 
            goods_id = v['id']          
            rec_id = v['rec_id']
            if v.has_key('nums'):
                nums = v['nums']
            else:
                nums = 1
            goods_info = store.get_goods_info(goods_id) 
            if not goods_info:
                return {'res':'not_goods'}
            
            #身上正在穿的物品不能出售
            my_bodyinfo = userinfo['my_bodyinfo']
            tmp_my_goods = my_bodyinfo.get('goods')
            if tmp_my_goods:
                for vv in tmp_my_goods:
                    if vv['rec_id'] ==rec_id and vv['id'] == goods_id:
                        return {'res':'not_sell'}
            
            #更新我的商品信息（删除待出售的商品，并保存最新的信息）
            res = store.set_new_mygoods(request, goods_info, userinfo, rec_id, nums)            
            if res['res'] != True:
                return  res
            if res.has_key('inlay'):#如果我的商品有镶嵌ID则出售镶嵌商品
                inlay_id = res['inlay']['inlay_id']            
                inlay_info = store.get_goods_info(inlay_id)
                if not inlay_info:
                    return {'res':'not_goods'}
                res = store.set_new_mygoods(request, inlay_info, userinfo, res['inlay']['rec_id'], nums)
                
            tmpDict = {'id':goods_id,
                       'rec_id':rec_id,
                       'nums':nums,
                       'type_1':goods_info['type_1'],
                       'type_2':goods_info['type_2'],
                       'type_3':goods_info['type_3']
                       }    
            tmpList.append(tmpDict)
            
        return {'res':True, 'goods':tmpList}
    
    #删除商品
    @staticmethod
    def deUserGoods(tmpUser,rec_id,id):
        '''删除用户的商品 rec_id：当前商品的记录id，id：当前商品的id'''
        goods_info = store.get_goods_info(id)
        if not goods_info:
            return {'res':'not_goods'}
        type_1=goods_info.get('type_1')
        type_2=goods_info.get('type_2')
        type_3=goods_info.get('type_3')
        tmpMyGoodsType_1 = tmpUser.m_userinfo.get('my_%s' % type_1)
       
        if not tmpMyGoodsType_1:
            return {'res':'not_goods'}
        tmpMyGoodsType_2 = tmpMyGoodsType_1.get(type_2)
        if not tmpMyGoodsType_2:
            return {'res':'not_goods'}
        tmpMyGoodsType_3 = tmpMyGoodsType_2.get(type_3)
        if not tmpMyGoodsType_3:
            return {'res':'not_goods'}
        tmpList = tmpMyGoodsType_3.get('info')
        if not tmpList:
            return {'res':'not_goods'}
        tmpIsDel = 0
        for v in tmpList:
            if v.get('rec_id')==rec_id and v.get('id')==id:
                tmpList.remove(v)
                tmpIsDel = 1
        if tmpIsDel:
            conn = mysql()
            tmpData = {'my_%s' % type_1:json_encode(tmpMyGoodsType_1)}
            conn.upData('t_user_data', tmpData, "WHERE uid = %d"%tmpUser.getUID())
        
        
            
        
    
    #续费商品
    @staticmethod
    def renew_goods(request, goods):
        user = UserManager.get_user_by_request(request)
        if not user:
            return {'res':'user_is_null'}
          
        userinfo = user.m_userinfo
        res = store.charge_goods(request, userinfo, goods, 1)
        userinfo = user.m_userinfo
        tmpList = []
        for v in goods:
            rec_id = v['rec_id']
            goods_id = v['id']
            goods_info = store.get_goods_info(goods_id)
            if not goods_info:
                return {"res":"not_goods"}
            type_1 = goods_info['type_1']
            type_2 = goods_info['type_2']
            type_3 = goods_info['type_3']           
            my_goods = userinfo['my_%s' % type_1]
            
            if my_goods:
                if not my_goods.get(type_2):
                    return {"res":"not_goods"}
                if not my_goods[type_2].get(type_3):
                    return {"res":"not_goods"}
                my_goods_list = my_goods[type_2][type_3]['info']
                #得到当前rec_id对应的商品信息
                my_goods_info = store.get_my_goods_info_by_rec_id(rec_id, my_goods_list)
                my_goods_info['sell_gold'] = store.get_one_of_my_goods_price(my_goods_info)                
                tmpList.append(my_goods_info)
        res['goods'] = tmpList
        return res

    
    #更新我的 新的商品列表并给用户加钱
    @staticmethod
    def set_new_mygoods(request, goods_info, userinfo, rec_id, nums):
        if not goods_info:
            return {"res":"not_goods"} 
        uid = userinfo['uid']
        nickname = userinfo['nickname']      
   
        #商品类型
        type_1 = goods_info['type_1']
        type_2 = goods_info['type_2']
        type_3 = goods_info['type_3']
        #得到我的穿着信息
        owner = UserManager.get_user_wear_info(uid)        
        if not owner['my_%s' % type_1]:
            return {"res":"not_goods"}
        my_goods = json_decode(owner["my_%s" % type_1])      
        if not my_goods.has_key(type_2):
            return {"res":"not_goods"}
        if not my_goods[type_2].has_key(type_3):
            return {"res":"not_goods"}
        #得到我的商品列表       
        my_goods_list = my_goods[type_2][type_3]['info']
        #得到当前rec_id对应的商品信息
        my_goods_info = store.get_my_goods_info_by_rec_id(rec_id, my_goods_list)
        if not my_goods_info:
            return {"res":"not_goods"} 
        #更新 我的 新的商品列表            
        my_goods[type_2][type_3]['info'].remove(my_goods_info)
        if  type_1 == 'props' and type_2 != 'attire':                    
            if my_goods_info['nums'] - nums > 0:
                my_goods_info['nums'] = my_goods_info['nums'] - nums
                my_goods[type_2][type_3]['info'].append(my_goods_info) 
            else:
                nums = my_goods_info['nums']            
        else:
            nums = 1 
           
        #------
          
        sell_gold = store.get_my_sell_price([my_goods_info]) 
        
        if sell_gold:
            sell_gold = sell_gold[0]['sell_gold']
      
        #保存新的商品列表到数据库
        store.save_my_goods(goods_info['type_1'], uid, my_goods)                    
        #记录出售日志
        store.set_sell_log(uid, nickname, goods_info, sell_gold)
        #为用户加钱
        tmpLogicMapObj = util.ConfigManager.getLogicInfo("default_logic")                       #获取默认配置项
        util.ConfigManager.setLogicInfoVal_Gold(tmpLogicMapObj, sell_gold)      #金币       
        util.CountUserUtil.judgeAndEditExt('sells_goods', request, userinfo['uid'], tmpLogicMapObj)       #加钱
        if my_goods_info.has_key('inlay'):
            if my_goods_info['inlay']['inlay_id']:
                return {"res":True, "inlay":my_goods_info['inlay']}
        return {"res":True}
    
    #获取我的商品信息，根据记录id
    @staticmethod    
    def get_my_goods_info_by_rec_id(rec_id, my_goods_info):
        for v in my_goods_info:
            if rec_id == v['rec_id']:
                return v
        return None
    
    #保存个人商品信息
    @staticmethod
    def save_my_goods(type_1, uid, my_goods):
        conn = mysql()
        data={"my_%s" % type_1:json_encode(my_goods)}
        conn.upData('t_user_data', data, " WHERE uid = '%s'"%uid)        
        UserManager.update_user(uid, {"my_%s" % type_1:my_goods})
        
    #更新个人商品信息
    @staticmethod
    def add_my_goods(buyer_uid, nickname, owner, goods_info, times, nums, inlay_last_rec_id=[], is_second=None, second_rec_id=None):
        
        goods_id = goods_info['goods_id']
        tmpGoodsRec = store.get_my_new_goods_rec(buyer_uid, nickname, owner, goods_info, times, nums, inlay_last_rec_id, is_second, second_rec_id) 
        my_goods = tmpGoodsRec['my_goods']
        last_ids = tmpGoodsRec['last_ids']
        
        store.save_my_goods(goods_info['type_1'], owner['uid'], my_goods) 
        conn = mysql()
#        udata = {"my_%s" % type_1:json_encode(my_goods)}
#        conn.upData("t_user_data",udata," WHERE uid = %d"%owner_uid)
        if goods_info['total'] != -1 and is_second == None:
            if goods_info['total'] - nums <= 0:               
                def_nums = goods_info['total']
            else:
                def_nums = nums
            upData = {"total":-def_nums}
            conn.upData('t_goods', upData, "WHERE `goods_id` = '%d' " % goods_id, 1)
            store.goods_list[goods_id]['total'] = store.goods_list[goods_id]['total'] - def_nums
        return last_ids
    
    #组装我的商品记录信息，把新商品和已经有的商品组合起来
    @staticmethod
    def get_my_new_goods_rec(buyer_uid, nickname, owner, goods_info, times, nums, inlay_last_rec_id=[], is_second=None, second_rec_id=None):
        '''把新的商品信息组合到历史购买信息中'''
        
        goods_id = goods_info['goods_id']#商品id
        inlay_id = goods_info['inlay_id']#镶嵌id
        owner_uid = owner['uid']         #拥有者id
        type_1 = goods_info['type_1']    #一级类   
        type_2 = goods_info['type_2']    #二级类
        type_3 = goods_info['type_3']    #三级类
        if not type_2:                   #设置默认类别
            type_2 = 'default'
        if not type_3:
            type_3 = 'default'
        
        #获取用户已经购买的商品信息    
        tmpTypeName = "my_%s" % type_1
        tmpObj = owner.get(tmpTypeName)
        if tmpObj:
            if type(tmpObj) == dict:
                my_goods = tmpObj
            else :
                my_goods = json_decode(tmpObj)
        else :
            my_goods = {}
        
#        if owner["my_%s" % type_1]:
#            if type(owner["my_%s" % type_1]) == dict:
#                my_goods = owner["my_%s" % type_1]
#            else :
#                my_goods = json_decode(owner["my_%s" % type_1])
#        else :
#            my_goods = {}
        
        #初始化新的商品信息    
        my_goods_info = {}
        
        #如果是背包类的道具，则覆盖以前相同的商品，并增加数量
        if type_1 == 'props' and type_2 != 'attire':            
            if my_goods.has_key(type_2):
                if my_goods[type_2].has_key(type_3):
                    for v in my_goods[type_2][type_3]['info']:
                        if v['id'] == goods_id:
                            my_goods[type_2][type_3]['info'].remove(v)
                            nums += v['nums']
  
            my_goods_info['nums'] = nums#购买数量
            nums = 1#背包类道具只循环一次，循环一次表示只增加一条记录
        
        
            
        #如果是家具的墙纸    则只保留一条记录，也只循环一次
        if type_1 =='furniture' and type_2 =='wallpaper':
            if my_goods.has_key('wallpaper'):
                if my_goods['wallpaper'].has_key(type_3):
                    my_goods['wallpaper'][type_3]['info'] = []
            nums=1
        
        last_rec_id = 1 
        
        i = 0   
        
        #初始化返回添加的rec_id   
        last_ids = []
        
        while i < nums:
            #如果不是道具类,或者道具服装类别的，数量都为1
            if type_1 != 'props' or (type_1 == 'props' and type_2 == 'attire'):               
                my_goods_info['nums'] = 1   
                                     
            if type_1 =='furniture':
                my_goods_info['x'] = random.randint(100, 560)
                my_goods_info['y'] = 0
            
            my_goods_info['got']=1  #默认标识商品已经领取
            #如果是礼品则则增加一个是否领取的标签，礼品超过指定数量后礼品架不能存放，需要发送一条礼品留言给用户，让用户领取
            if type_1 == 'present':                
                my_goods_info['z_1'] = goods_info['z_1']
                tmpMy_present = owner['my_present']                
                if tmpMy_present:
                    if type(tmpMy_present)!=dict:
                        tmpMy_present = json_decode(tmpMy_present)
                    if tmpMy_present:
                        tmpPresentNums = store.get_my_goods_nums(tmpMy_present,{"z_1":goods_info['z_1']})
                        
                        if goods_info['z_1']==0:
                            if (tmpPresentNums +i+1)>  const.Config_small_present_notice_nums() : 
                                my_goods_info['got']=0
                        if goods_info['z_1']==1:
                          
                            if (tmpPresentNums +i+1)>  const.Config_big_present_notice_nums() : 
                                my_goods_info['got']=0 
                   
            my_goods_info['rec_id'] = last_rec_id#记录id
            my_goods_info['id'] = goods_id #商品ID
            my_goods_info['buyer'] = buyer_uid#购买者
            my_goods_info['nickname'] = nickname#购买者
            my_goods_info['sell_gold'] = 0 #初始化出售价格
            if goods_info['gold']:
                my_goods_info['sell_gold'] = int(goods_info['gold'] * const.Config_GoodSellPer() / 100.0)#花费金币
            if goods_info['money']:
                my_goods_info['sell_gold'] = my_goods_info['sell_gold'] + int(goods_info['money'] * const.Config_MoneyGoodSellPer() / 100.0 * const.Config_GoodSellPer() / 100.0)
            my_goods_info['buy_gold'] = goods_info['gold']#花费金币
            my_goods_info['buy_money'] = goods_info['money']#花费比索
#            if inlay_last_rec_id:
#                inlay_rec_id = inlay_last_rec_id[i]
#            else:
#                inlay_rec_id = 0
#            my_goods_info['inlay'] = {"inlay_id":inlay_id, "rec_id":inlay_rec_id}#镶嵌信息
#            my_goods_info['z_1'] = goods_info['z_1']#层级1
#            my_goods_info['z_2'] = goods_info['z_2']#层级2
            my_goods_info['buy_time'] = int(time.time())#购买开始时间           
            if times == -1:#如果是永久则到期时间为-1，否是在当前时间起+时长
                my_goods_info['limit_time'] = times
            else:
                my_goods_info['limit_time'] = int(time.time() + times)#到期时间   
            
            #计算新商品的到期时间和记录id并组合到到我历史购买的商品中      
            #如果已经有过购买记录
            if my_goods.has_key(type_2):
                #如果是续费购买，则增加续费时间，并保存到历史购买商品中
                if is_second:
                    #根据续费的记录id和我的历史购买记录取到唯一的已购买商品信息
                    last_my_goods_info = store.get_my_goods_info_by_rec_id(second_rec_id, my_goods[type_2][type_3]['info'])
                    my_goods_info = last_my_goods_info
                    
                    if times == -1:
                        my_goods_info['limit_time'] = times
                    else:
                        s_time = my_goods_info['limit_time']
                        now_t = int(time.time())
                        if s_time < now_t:
                            s_time = now_t
                        my_goods_info['limit_time'] = int(s_time + times)#到期时间
                    my_goods[type_2][type_3]['info'].remove(last_my_goods_info)
                    my_goods[type_2][type_3]['info'].append(my_goods_info.copy())
                else:      
                    #不是续费，则追加记录
                    if not my_goods[type_2].has_key(type_3):
                        my_goods[type_2][type_3] = {'last_rec_id':0, 'info':[]}
                    last_rec_id = my_goods[type_2][type_3].get('last_rec_id') + 1
                    my_goods_info['rec_id'] = last_rec_id 
                   
                    my_goods[type_2][type_3]['last_rec_id'] = last_rec_id                          
                    my_goods[type_2][type_3]['info'].append(my_goods_info.copy())
            
            #如果没有购买记录，则新初始化一条记录，并把新商品添加到购买记录中
            else: 
                
                my_goods[type_2] = {}                
                my_goods[type_2][type_3] = {}
                my_goods[type_2][type_3]['last_rec_id'] = last_rec_id
                my_goods[type_2][type_3]['info'] = []
            
                my_goods[type_2][type_3]['info'].append(my_goods_info.copy())
            i += 1
           
            last_ids.append(last_rec_id)   
        
       
        return {"my_goods":my_goods,"last_ids":last_ids}
    
    
    #更新商品信息 dict={"total":99}
    @staticmethod
    def up_goods(goods_id, dict):
        goods = store.goods_list[goods_id]
        for k, v in dict.iteritems():
            goods[k] = v
            
    #商品续费
    @staticmethod
    def renewals(request, owner_uid, goods_id):  
        pass
    

    
    #查询商品信息
    @staticmethod
    def get_goods_info(*goods_id):        
        tmpList = {}
        for v in goods_id:
            if store.goods_list.has_key(v):
                tmpList[v] = store.goods_list[v]
        if len(goods_id) == 1:            
            if store.goods_list.has_key(goods_id[0]):       
                return tmpList[goods_id[0]]
        else:
            return tmpList
    
    #查询商品信息, 商品不存在, 则发错误信息, 返回None; 只查询一个 id，返回商品对象, 否则返回对象字典; 
    @staticmethod
    def getGoodsInfoExt(cmd, request, *goods_id):        
        tmpList = {}
        bNotGood = False
        for v in goods_id:
            if store.goods_list.has_key(v):
                tmpList[v] = store.goods_list[v]
            else:
                bNotGood = True
                log.print_warning(logger, "store getGoodsInfoExt exec, good_id:[%s] not exist" % v)
                break
            
        if bNotGood: #有商品不存在
            tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
            tmpSendMsgUtil.update_res("not_goods")
            tmpSendMsgUtil.send(cmd, request)
            return None
            
        if len(goods_id) == 1:  
            return tmpList[goods_id[0]]
        else:
            return tmpList
    
    #统计商品价格 （商品信息，时间类型，数量,type,是否计算镶嵌价格 ）
    @staticmethod    
    def total_buy_money(goods_info, times, nums, buy_second=None, total_inlay=True):
        inlay_info = {"gold":0, "money":0, "gold1":0, "money1":0, "gold2":0, "money2":0, "gold3":0, "money3":0}
        if buy_second:                      
            time1 = goods_info['time1']
            time2 = goods_info['time2']
            time3 = goods_info['time3']
        inlay_id = goods_info['inlay_id']#镶嵌商品ID
        is_inlay = goods_info['is_inlay']
        if total_inlay:  
            if inlay_id and is_inlay:
                inlay_info = store.get_goods_info(inlay_id)  
                if not inlay_info:
                    return {'res':'not_goods'}     
                      
        buy_gold = buy_money = 0
        #商品总价格=（商品价格+镶嵌商品价格）*商品个数
        if not buy_second:
            buy_gold += (goods_info['gold'] + inlay_info['gold']) * nums  #金币
            buy_money += (goods_info['money'] + inlay_info['money']) * nums #比索 
        else:
            if times == time1:                    
                buy_gold += (goods_info['gold1'] + inlay_info['gold1']) * nums  #金币
                buy_money += (goods_info['money1'] + inlay_info['money1']) * nums #比索 
            elif times == time2: 
                buy_gold += (goods_info['gold2'] + inlay_info['gold2']) * nums
                buy_money += (goods_info['money2'] + inlay_info['money2']) * nums
            elif times == time3:                   
                buy_gold += (goods_info['gold3'] + inlay_info['gold3']) * nums
                buy_money += (goods_info['money3'] + inlay_info['money3']) * nums
        return {"buy_gold":buy_gold, "buy_money":buy_money}
        
    #插入购买记录
    @staticmethod
    def set_buy_log(buyer_uid, buyer_nickname, owner_uid, owner_nickname, goods_info, buy_gold, buy_money, buy_second=0, remark=None):
        goods_id = goods_info['goods_id']
        goods_name = goods_info['goods_name']
        type_1 = goods_info['type_1']
        type_2 = goods_info['type_2']
        type_3 = goods_info['type_3']
        if not remark:
            remark = ''
        tmpDataDict = {"buyer_uid":buyer_uid, "buyer_nickname":buyer_nickname,
                "owner_uid":owner_uid, "owner_nickname":owner_nickname,
                "goods_id":goods_id, "goods_name":goods_name,
                "type_1":type_1, "type_2":type_2, "type_3":type_3,
                "timeline":time.strftime('%Y-%m-%d %H:%M:%S'),
                "buy_gold":buy_gold, "buy_money":buy_money, "buy_second":buy_second, "remark":remark}
        #conn = mysql()
        #conn.inData(table='t_log_buy', data=tmpDataDict)
        tmpStrSql = mysql.createInserStrSql('t_log_buy', tmpDataDict)
        util.SqlThread.addSqlStr(tmpStrSql) #线程写记录
        return True
    
    #插入出售记录
    @staticmethod
    def set_sell_log(uid, nickname, goods_info, sell_gold):
        goods_id = goods_info['goods_id']
        goods_name = goods_info['goods_name']
        type_1 = goods_info['type_1']
        type_2 = goods_info['type_2']
        type_3 = goods_info['type_3']
        tmpDataDict = {"uid":uid, "nickname":nickname,
                "goods_id":goods_id, "goods_name":goods_name,
                "type_1":type_1, "type_2":type_2, "type_3":type_3,
                "timeline":time.strftime('%Y-%m-%d %H:%M:%S'),
                "sell_gold":sell_gold}
        #conn = mysql()
        #conn.inData(table='t_log_sell', data=tmpDataDict)
        tmpStrSql = mysql.createInserStrSql('t_log_sell', tmpDataDict)
        util.SqlThread.addSqlStr(tmpStrSql) #线程写记录
        return True
    
    #根据商品信息获取我的商品信息
    @staticmethod
    def get_my_goods_info(uid, goods_info):
        type_1 = goods_info['type_1']
        type_2 = goods_info['type_2']
        type_3 = goods_info['type_3']      
        owner = UserManager.get_user_by_uid(uid).m_userinfo
        if not owner:
            owner = UserManager.get_user_wear_info(uid)
        if not owner['my_%s' % type_1]:
            return None
        if type(owner["my_%s"%type_1])!=dict:           
            my_goods = json_decode(owner["my_%s" % type_1]) 
        else:
            my_goods = owner["my_%s" % type_1]
        if not my_goods.has_key(type_2):
            return None           
        #得到我的商品列表
        my_goods_list = []
        if my_goods.get(type_2):
            if my_goods[type_2].get(type_3):
                my_goods_list = my_goods[type_2][type_3]['info']
        return {"my_goods_list":my_goods_list, "my_goods":my_goods}
    
    #根据类别查我的商品信息
    @staticmethod
    def get_my_goods_by_type(uid, type_1, type_2, type_3, begin, nums):
        owner = UserManager.get_user_wear_info(uid)
        if not owner:
            return {"res":"not_goods"}
        tmpStrType1 = 'my_%s' % type_1
        if not owner.get(tmpStrType1):
            return {"res":"not_goods"}
        my_goods = json_decode(owner["my_%s" % type_1]) 
        if type_2 == 'all':
            type_list = my_goods
            if not type_list:
                return {"res":"not_goods"} 
            my_goods_list = []
            for k, v in type_list.iteritems():
                for kk , vv in v.iteritems():
                    for vvv in vv['info']:
                        my_goods_list.append(vvv)
        else:
            if not my_goods.has_key(type_2):
                return {"res":"not_goods"} 
            #得到我的商品列表
            if type_3 == 'all':
                type_list = my_goods[type_2]
                my_goods_list = []
                for k, v in type_list.iteritems():
                    for vv in v['info']:
                        my_goods_list.append(vv)
            else:
                if not my_goods[type_2].has_key(type_3):
                    return {"res":"not_goods"} 
                my_goods_list = my_goods[type_2][type_3]['info']  
        tmpList = store.get_my_sell_price(my_goods_list)       
        tmpList = tmpList[begin - 1:begin + nums - 1] 
        return {"res":True, "list":tmpList, "count":len(my_goods_list)}
    
    #根据我的商品列表计算出出售价格
    @staticmethod
    def get_my_sell_price(list):
        new_list = []
        for vvv in list: 
            vvv['sell_gold'] = store.get_one_of_my_goods_price(vvv)
            new_list.append(vvv)
        return new_list
    
    #获取商品的出售价格  
    @staticmethod
    def get_one_of_my_goods_price(vvv):
        return int(store.get_one_of_my_goods_value(vvv)* (const.Config_GoodSellPer() / 100.0))       
    
    #获取商品的折旧价 
    @staticmethod
    def get_one_of_my_goods_value(vvv):
        price = 0
        if vvv:
            days = int((int(time.time()) - vvv['buy_time']) / 24 / 3600)
            old_price = 0
            #if not vvv.has_key('nums'):
            nums = 1
            
            #出售商品价格=     购买价格     *  折旧比例的N次方N=天数     
            if vvv['buy_gold']:                
                old_price = int(vvv['buy_gold'] * ((100.0 - const.Config_Old_Per()) / 100.0) ** days ) *nums  
                   
                if int((vvv['buy_gold'] * const.Config_Min_SellPer()) * 1.0 / 100.0) *nums >= old_price:
                   
                    old_price = int((vvv['buy_gold'] * const.Config_Min_SellPer()) * 1.0 / 100.0) *nums                         
            price = price + old_price                  
            old_price = 0   
            if vvv['buy_money']:
                old_price = int(vvv['buy_money'] * ((100.0 - const.Config_Old_Per()) / 100.0) ** days * const.Config_MoneyGoodSellPer() / 100.0 ) *nums
                if int((vvv['buy_money'] * const.Config_MoneyGoodSellPer() / 100.0) * 1.0 * const.Config_Min_SellPer() / 100.0) *nums >= old_price:
                    
                    old_price = int((vvv['buy_money'] * const.Config_MoneyGoodSellPer() / 100.0) * 1.0 * const.Config_Min_SellPer() / 100.0) *nums            
            price = price + old_price             
        return price
    
    #更改我的个人商品信息(uid,记录id，商品信息，我的商品信息)
    @staticmethod
    def set_goods_info(uid, rec_id, goods_info, my_goods_info, dict):        
        
        my_goods_list = my_goods_info['my_goods_list']
        my_goods = my_goods_info['my_goods']
        last_my_goods_info = store.get_my_goods_info_by_rec_id(rec_id, my_goods_list)
        if not last_my_goods_info:
            return {"res":"not_goods"}
        my_goods_list.remove(last_my_goods_info)
        for k, v in dict.iteritems():
            if v:
                if type(v) is dict:
                    for kk, vv in v.iteritems():
                        last_my_goods_info[k][kk] = vv
                else:        
                    last_my_goods_info[k] = v 
        my_goods_list.append(last_my_goods_info)
        
        type_1 = goods_info['type_1']
        type_2 = goods_info['type_2']
        type_3 = goods_info['type_3']
        my_goods[type_2][type_3]['info'] = my_goods_list
        #存数据库
        store.save_my_goods(type_1, uid, my_goods)
        
#        new_goods = json_encode(my_goods)
        
#        conn = mysql()
#        sql = "UPDATE t_user_data SET  `%s` = '%s'   WHERE uid = '%d'" % ("my_%s" % type_1, new_goods, uid)
#        conn.query(sql)
#        UserManager.update_user(uid, {"my_%s" % type_1:new_goods})
        
        return {"res":True}
   
    #查询商品数量  goods_id=[1001,1002]
    @staticmethod
    def get_goods_nums(request, data): 
        goods_id = data['goods_id']
        tmpList = []
        if goods_id:
            for v in goods_id:
                goods_info = store.get_goods_info(v)
                if not goods_info:
                    return {'res':'not_goods'}
                dic = {'goods_id':v, 'total':goods_info['total']}
                tmpList.append({'goods_id':v, 'total':goods_info['total']})
            return {'res':True, 'list':tmpList}

        if data.has_key('type_1'):
            type_1 = data['type_1']
        else:
            return {'res':'not_goods'}
        if data.has_key('type_1'):
            type_2 = data['type_2']
        else:
            return {'res':'not_goods'}
        if data.has_key('type_1'):
            type_3 = data['type_3']
        else:
            return {'res':'not_goods'}
       
        for k, v in store.goods_list.iteritems():
            
            dic = {}  
            
            if type_2 == 'all':
                if type_3 == 'all':
                    dic = {'goods_id':v['goods_id'], 'total':v['total']}
                    tmpList.append(dic)
                else:
                    if v['type_3'] == type_3 :  
                        dic = {'goods_id':v['goods_id'], 'total':v['total']}
                        tmpList.append(dic)                    
            
            else:
                if v['type_1'] == type_1 and v['type_2'] == type_2 :                
                    if type_3 == 'all':
                        dic = {'goods_id':v['goods_id'], 'total':v['total']}
                        tmpList.append(dic)
                    else:
                        if v['type_3'] == type_3 :  
                            dic = {'goods_id':v['goods_id'], 'total':v['total']}
                            tmpList.append(dic)   
        return {'res':True, 'list':tmpList} 

    #获取我的商品数量
    @staticmethod
    def get_my_goods_nums(my_goods_list,where_dict=None):
        j = 0
        for k, v in my_goods_list.iteritems():			
			for kk, vv in v.iteritems():
			    for vvv in vv['info']:      
			        if where_dict:
			            k=0
			            l=0
			            for kkkkk,vvvvv in where_dict.iteritems(): 
			                if vvv.has_key(kkkkk):                           
			                    if vvv[kkkkk] == vvvvv:
			                        k= 1
			                    else:
			                        l=1
			            if l!=1 and k==1:
			                j += 1
			        else:
			            j += 1
        return j
            
    
    @staticmethod
    def send_goods_to_somebody(tmpUser, tmpGoodsList):
        '''给某人送商品'''
        if not tmpUser or not isinstance(tmpGoodsList, list):
            return
       
        tmpUserInfo = tmpUser.getUserInfoObj()
        
        tmpGoodsList1=[]
        for goods_id in tmpGoodsList:
            goods_info={}
            goods_info = store.get_goods_info(goods_id)
            if not goods_info:
                continue;
            tmpGoodsList1.append(goods_info)
         
        if not tmpGoodsList1:
            return   
        tmpGoodsList = util.sortArrDict(tmpGoodsList1, 'level') 
            
        my_goods = {}
        for goods_info in tmpGoodsList:         
            tmp_my_goods={}
            tmpRec={}           
            if not goods_info:
                continue;
            times = goods_info.get('time')            
           
            type_1 = goods_info.get('type_1')
            type_2 = goods_info.get('type_2')
            type_3 = goods_info.get('type_3')
            
            #如果用户没有购买过商品，则初始化购买记录
            if not my_goods.get("my_%s"%type_1):
                my_goods["my_%s"%type_1]={}
            if not my_goods["my_%s"%type_1].get(type_2):
                my_goods["my_%s"%type_1][type_2]={}
            if not my_goods["my_%s"%type_1][type_2].get(type_3):
                my_goods["my_%s"%type_1][type_2][type_3]={'info':[],'last_rec_id':0}
            
            #组装购买记录   
            tmpRec = store.get_my_new_goods_rec(0, '系统', tmpUserInfo, goods_info, times, 1, 0, 0, 0)
            tmp_my_goods = tmpRec['my_goods']
            
            if tmp_my_goods:
                #更新内存对应用户商品信息
                tmpUserInfo["my_%s"%type_1] = tmp_my_goods
                my_goods["my_%s"%type_1] =  tmp_my_goods
                
                store.set_buy_log(0, '系统', tmpUser.getUID(), tmpUser.getNickname(), goods_info, 0, 0)
             
        #更新数据库表     
        if my_goods:
            upData = {}
            for k,v in my_goods.iteritems():                
                upData[k] = json_encode(v)
            conn = mysql()
            conn.upData('t_user_data', upData, "WHERE uid = %d"% tmpUser.getUID())
            #print UserManager.get_user_by_request(request).m_userinfo
            #UserManager.update_user(tmpUserInfo['uid'], my_goods)







